BASIC PYTHON FOR RESEARCHERS

by Megat Harun Al Rashid bin Megat Ahmad
last updated: April 14, 2016


3. Conditional Expressions

$Python$ conditional expressions include the $if/elif/else$ statement. In addition the $for$ and $while$ statements can be used in conditional looping. $Python$ also has the $enumerate$( ) function for conditional looping.


3.1 The if/else condition

The $if/else$ conditional expression allows statement to be executed if a condition is fulfilled:


In [1]:
# Calculate the remainder of a divisional operation
x = 56
y = 3
z = x % y         # Modulo operation

if z > 0:
    print ("The remainder of %d divided by %d is %d" % (x,y,z))
else:
    print "There's no remainder"


The remainder of 56 divided by 3 is 2

The $z = x$ % $y$ operation means that the remainder of $x$ when divided with $y$ will be assigned to $z$. The $if/else$ conditional expression above resulted in the printing of the variable $z$ if its value is positive, i.e. if $x$ when divided with $y$ has a remainder. If this condition is not fulfilled, then the text "There's no remainder" will be printed.

Statements inside conditional expression must be indented with space (not tab). The indentation must be consistent throughout the condition.


3.2 The if/elif/else condition

The $if/elif/else$ conditional expression allows multiple conditions to be applied.


In [2]:
# Compare the values of two integers

int1 = 45
int2 = 55

if int1 > int2:
    print "%d is larger than %d" % (int1,int2)
elif int1 == int2:
    print "%d is equal to %d" % (int1,int2)
else:
    print "%d is less than %d" % (int1,int2)


45 is less than 55

In the example above, the first condition always use the $if$ condition expression (i.e. $int1$ > $int2$). Only if this is not fulfilled will the second condition be evaluated i.e. the $elif$ condition expression. If this condition is also not fulfilled, then the $else$ condition statement will be executed.

In multiple conditional expressions, all the conditions will be evaluated in sequence. When one of the condition is fulfilled, the sequential evaluation will stop and the statement for that conditions will be executed.

Some of the conditional operators that can be used in a conditional expression:

Condition Function
> more than
< less than
>= equal or more than
<= equal or less than
== equal to
!= not equal to
and more than one conditional operations are true
or either one conditional operations is true

In general, the multiple conditional expressions format is:

if (condition/s 1):

statement 1.1
statement 1.2
......

elif (condition/s 2):

statement 2.1
......

elif (condition/s 3):

statement 3.1
......

......
......
......

else:

statement
......

The statement in each conditional expression can also be a conditional expression.

Example 3.1: Determine the maximum and minimum of three different integers: 34,12,67.


In [3]:
x = 34
y = 12
z = 67

if x > y:
    if y > z:
        print 'Maximum integer is %d' % x
        print 'Minimum integer is %d' % z
    elif z > x:
        print 'Maximum integer is %d' % z
        print 'Minimum integer is %d' % y
    else:
        print 'Maximum integer is %d' % x
        print 'Minimum integer is %d' % y
        
else:  # y > x
    if x > z:
        print 'Maximum integer is %d' % y
        print 'Minimum integer is %d' % z
    elif z > y:
        print 'Maximum integer is %d' % z
        print 'Minimum integer is %d' % x
    else:
        print 'Maximum integer is %d' % y
        print 'Minimum integer is %d' % x


Maximum integer is 67
Minimum integer is 12

Example 3.2: Use only one type of conditional operator for Exercise 3.1.


In [4]:
x = 34
y = 12
z = 67

if x > y > z:
    print 'Maximum integer is %d' % x
    print 'Minimum integer is %d' % z

elif x > z > y:
    print 'Maximum integer is %d' % x
    print 'Minimum integer is %d' % y
    
elif y > x > z:
    print 'Maximum integer is %d' % y
    print 'Minimum integer is %d' % z

elif y > z > x:
    print 'Maximum integer is %d' % y
    print 'Minimum integer is %d' % x

elif z > x > y:
    print 'Maximum integer is %d' % z
    print 'Minimum integer is %d' % y

else:
    print 'Maximum integer is %d' % z
    print 'Minimum integer is %d' % x


Maximum integer is 67
Minimum integer is 12

Exercise 3.1: What if two or all integers have the same value. Try this and run the codes that solve Examples 3.1 and 3.2.

Codes in Example 3.1 seems more robust but 3.2 can be made more robust adding '>=' instead of '>'.


In [5]:
x = 78
y = 78
z = 99

if x >= y >= z:
    print 'Maximum integer is %d' % x
    print 'Minimum integer is %d' % z

elif x >= z >= y:
    print 'Maximum integer is %d' % x
    print 'Minimum integer is %d' % y
    
elif y >= x >= z:
    print 'Maximum integer is %d' % y
    print 'Minimum integer is %d' % z

elif y >= z >= x:
    print 'Maximum integer is %d' % y
    print 'Minimum integer is %d' % x

elif z >= x >= y:
    print 'Maximum integer is %d' % z
    print 'Minimum integer is %d' % y

else:
    print 'Maximum integer is %d' % z
    print 'Minimum integer is %d' % x


Maximum integer is 99
Minimum integer is 78

3.3 The for and while conditions

The $for$ and $while$ functions can be used to do repetitive action. The indentation with space (not tab) for statements inside the loop is also applied and consistent throughout the condition.


In [6]:
for i in range(0,5,1):
    print i


0
1
2
3
4

Here the variable $i$ will be assigned the value of $0$ and cyclically incremented $5$ times by adding the integer $1$ to it each time. Only integer values are accepted in the parenthesis of the range statement. The first integer is the intial value of the $i$ variable, the second integer indicates (not-inclusive) the limiting value of the $i$ variable and the third integer represent the integer added to the variable $i$ for each cycles.


In [7]:
for i in range(4,17,3):
    print i*2


8
14
20
26
32

The conditional looping can be nested as examplified below:


In [8]:
for i in range(1,6,1):
    for j in range(6,11,1):
        print '%d x %d = %d' % (i,j,i*j)


1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
1 x 10 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

It is also possible to loop into the elements of a string (i.e. a $list$).


In [9]:
for name in 'Numpy':
    print name


N
u
m
p
y

The $while$ function works similarly like $for$ but initialization of the variable is performed before the $while$ statement and incrementing process is carried out as part of the loop argument.


In [10]:
z = 0
while z < 27:
    print z
    z = z + 6


0
6
12
18
24

3.3 The $enumerate$( ) function

The $enumerate$( ) function will make the $for$ looping condition looking more comprehensible. The argument for this function is a $list$.


In [11]:
for i,j in enumerate('Numpy'):
    print i, '\t', j


0 	N
1 	u
2 	m
3 	p
4 	y

In [12]:
for item in enumerate('Numpy'):
    print item


(0, 'N')
(1, 'u')
(2, 'm')
(3, 'p')
(4, 'y')

The $enumerate$( ) function allows the extraction of both the default position and its element of a $list$. In the first example, the two variables $i$ and $j$ will be assigned the $list$ default positional number and its element, respectively. In the second example, the variable $item$ will be assigned a tuple that consists the pair of default positional number and its element of the $list$.

The default positional number can be initiated to a different number. This can be done by passing the initial number as another argument in the $enumerate$( ) function.


In [13]:
for item in enumerate('Numpy',5):
    print item


(5, 'N')
(6, 'u')
(7, 'm')
(8, 'p')
(9, 'y')

More on conditional expressions and looping can be found on https://docs.python.org/2/tutorial/controlflow.html